<?php
declare(strict_types=1);

namespace App\Common\Modular\User\Serve;

use App\Common\Modular\User\Model\LevelModel;
use Core\Basics\BasicsModel;
use Core\Basics\BasicsServe;
use Zms\Exception\AppException;
use Zms\Exception\ValidateException;

/**
 * 用户等级
 * @method LevelModel getModel()
 */
class LevelServe extends BasicsServe
{
    public static function model(): string
    {
        return LevelModel::class;
    }

    /**
     * 会员等级数据字典
     * @return array{value:string,label:string}[]
     */
    public function dictionary(): array
    {
        $data = $this->search(['status' => 1])->select(['id as value', 'name as label'])->orderByRaw('sort DESC,id DESC')->get()->toArray();
        foreach ($data as &$item) {
            $item['value'] = (string)$item['value'];
        }
        return $data;
    }


    /**
     * 新增会员等级
     * @throws ValidateException
     */
    public function created(array $values): BasicsModel|false
    {
        if ($this->exists(['name' => $values['name']])) {
            throw new ValidateException("会员等级‘{$values['name']}’已存在");
        }
        return parent::created($values); // TODO: Change the autogenerated stub
    }


    /**
     * @describe 编辑会员等级
     * @user zlf <zms-pro@qq.com> 2025/3/10
     * @param array $data
     * @param array|string|null $where
     * @param bool $returnModel
     * @return bool|BasicsModel
     * @throws ValidateException
     * @throws AppException
     */
    public function updated(array $data, array|string|null $where = null, bool $returnModel = false): bool|BasicsModel
    {
        if ($this->exists("(`name`=? AND `id`!=?)", [$data['name'], $data['id']])) {
            throw new ValidateException("会员等级‘{$data['name']}’已存在");
        }
        return parent::updated($data, $where, $returnModel); // TODO: Change the autogenerated stub
    }
}